
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/attend_record_calendar_page.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/even/attend_record_calendar_refresh_even.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/widgets/modify_personal_clock_record_widget.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_index/check_in_record_index_page.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/pages/check_in_statistics_list_response_bean.dart';
import 'package:e_reception_flutter/ui/mark/matching_mark_list/matching_mark_list_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/mark_info_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

/// 刷脸列表项组件显示
///
class TerminalFaceBrushingRecordPage extends StatefulWidget {
  // final CheckInStatisticsListItemBean itemBean;
  final String hsn;
  final String title;
  const TerminalFaceBrushingRecordPage({Key key, this.title, this.hsn}) : super(key: key);

  @override
  _TerminalFaceBrushingRecordPageState createState() => _TerminalFaceBrushingRecordPageState();
  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context,String title,String hsn) {
    return RouterUtils.routeForFutureResult(
      context,
      TerminalFaceBrushingRecordPage(
        title: title,
        hsn: hsn,
      ),
    );
  }
}

class _TerminalFaceBrushingRecordPageState extends State<TerminalFaceBrushingRecordPage> {
  DateTime time = DateTime.now();
  int month;
  int year;
  int day;
  int recordNum = 0;
  CommonListPageWidgetState<CheckInStatisticsListItemBean,
      CheckInStatisticsListResponseBean> listState;

  CheckInStatisticsListResponseBean data = CheckInStatisticsListResponseBean();
  @override
  void initState() {
    super.initState();
    month = time.month;
    year = time.year;
    day = time.day;
  }
  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _toTopBarWidget(),
            _toTopBarDateTimeWidget(),
            _toBody(),
          ],
        ),
      ),
    );

  }

  // int getCurrentMonthTimeStramp() {
  //   DateTime _dateTime = DateTime?.parse(DateUtil.getDateTimeByMs((widget?.itemBean?.firsttime??0)*1000)?.toString() ?? DateTime.now().toString());
  //   if (_dateTime == null) {
  //     return null;
  //   }
  //   return (DateTime(_dateTime.year, _dateTime.month, _dateTime.day)
  //       .millisecondsSinceEpoch /
  //       1000)
  //       .floor();
  // }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "${widget?.title}",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _toTopBarDateTimeWidget() {
    return Container(
      height: 50,
      alignment: Alignment.centerLeft,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              DateTime nextMonth = DateTime(year, month, day - 1);
              year = nextMonth.year;
              month = nextMonth.month;
              day = nextMonth.day;
              time = nextMonth;
              listState?.viewModel?.refreshMultiPage();
              // time = getCurrentMonthTimeStramp(nextMonth);
              // if(dayUserPunchList == null && dayUserPunchList?.length == 0)onTapNextDay = false;
              setState(() {});
            },
            child: Container(
                width: 40,
                alignment: Alignment(0.7,0),
                child: Image.asset(
                  "images/calendar_previous_ico.png",
                  width: 16,
                )),
          ),
          Container(
            // width: (_getDateStr(DateTime.now())?.contains(" ")??false)? 115 : 85,
            child: Center(
              child: Text(
                _getDateStr(DateTime(year, month, day)),
                // "$month月$day日",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  fontSize: 15,
                  height: 1.2,
                ),
              ),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              if((_getDateStr(DateTime(year, month, day))?.contains("今天")??false)){
                return;
              }else{
                DateTime nextMonth = DateTime(year, month, day + 1);
                year = nextMonth.year;
                month = nextMonth.month;
                day = nextMonth.day;
                time = nextMonth;
                listState?.viewModel?.refreshMultiPage();
              }
              setState(() {});
            },
            child: Opacity(
              opacity: (_getDateStr(DateTime(year, month, day))?.contains("今天")??false) ? 0.3:1,
              child: Container(
                  width: 40,
                  alignment: Alignment(-0.7,0),
                  child: Image.asset(
                    "images/calendar_next_ico.png",
                    width: 16,
                  )),
            ),
          ),
          Spacer(),
          Padding(
            padding: const EdgeInsets.only(right: 15),
            child: Container(child: Text("共${recordNum}人刷脸",style: TextStyle(color:ThemeRepository.getInstance().getHintGreenColor_5E687C(), fontSize: 12),)),
          ),
        ],
      ),
    );
  }

  ///获取日期串
  String _getDateStr(DateTime currentDateTime){
    if(currentDateTime == null){
      return "-";
    }
    final DateTime nowInitDateTime = _getNowInitDateTime();

    StringBuffer stringBuffer = StringBuffer();
    if(nowInitDateTime.year == currentDateTime.year) {
      if (nowInitDateTime == currentDateTime) {
        stringBuffer.write("今天 ");
      } else if (nowInitDateTime == currentDateTime.add(Duration(days: 1))) {
        stringBuffer.write("昨天 ");
      } else if (nowInitDateTime == currentDateTime.add(Duration(days: 2))) {
        stringBuffer.write("前天 ");
      }
    }else{
      stringBuffer.write("${currentDateTime.year}");
    }

    stringBuffer.write("${currentDateTime.month}月${currentDateTime.day}日");
    return stringBuffer.toString();
  }

  ///获取现在凌晨时间
  DateTime _getNowInitDateTime(){
    final DateTime nowDateTime = DateTime.now();
    final DateTime nowInitDateTime = DateTime(nowDateTime.year,nowDateTime.month,nowDateTime.day);
    return nowInitDateTime;
  }

  Widget _toBody(){
    return Expanded(
      child: _toColumnListItemBeanWidget(),
    );
  }

  Widget _toMainRowWidget(CheckInStatisticsListItemBean itemBean) {
    return GestureDetector(
      onTap: (){
        //单人整日数据列表
        ModifyPersonalClockRecordWidget.navigatorPush(
            context,
            // smallCardValue,
            // smallStatusCardColor,
            VgDateTimeUtils.getStringToIntMillisecond(DateTime(year, month, day)?.toString()),
            itemBean?.fuid,
            DateTime(year, month, day),
                () {
              VgEventBus.global.send(AttendRecordCalendarRefreshEven());
            });
      },
      child: Container(
        height: 60,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: Row(
          children: <Widget>[
            SizedBox(width: 15),
            _toHeadPicWidget(context,itemBean),
            SizedBox(width: 9),
            Expanded(child: _toColumnWidget(itemBean)),
            SizedBox(width: 15),
          ],
        ),
      ),
    );
  }

  Widget _toHeadPicWidget(BuildContext context,CheckInStatisticsListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        VgPhotoPreview.single(
            context,
            showOriginEmptyStr(itemBean?.putpicurl) ??
                showOriginEmptyStr(itemBean?.napicurl ?? "") ??
                ( ""),
            loadingImageQualityType: ImageQualityType.middleDown);
        // if(delflgUser(context)){
        //   return;
        // }
        // PersonDetailPage.navigatorPush(context, widget?.itemBean?.fuid,pages: "CheckInStatisticsPage");
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: VgCacheNetWorkImage(
          showOriginEmptyStr(itemBean?.putpicurl) ??
              (showOriginEmptyStr(itemBean?.napicurl) ?? ""),
          width: 37,
          height: 37,
          imageQualityType: ImageQualityType.middleUp,
          defaultPlaceType: ImagePlaceType.head,
          defaultErrorType: ImageErrorType.head,
        ),
      ),
    );
  }

  ///是否显示最大时间
  bool isShowMaxTime(int minTime, int maxTime) {
    if (minTime == null || minTime <= 0 || maxTime == null || maxTime <= 0) {
      return false;
    }
    int time = (maxTime - minTime).abs();
    if(minTime == maxTime || time<60){
      return false;
    }
    // if (minTime > maxTime) {
    //   //最小与最大对调位置
    //   int time;
    //   time = itemBean?.firsttime;
    //   itemBean?.firsttime = itemBean?.lasttime;
    //   itemBean?.lasttime = time;
    //   return true;
    // }
    return true;
  }

  Widget _toColumnListItemBeanWidget() {
    // String sDateTime =
    // ((DateTime(time.year, time.month, time.day)?.millisecondsSinceEpoch ?? 0) /
    //     1000)
    //     .floor()
    //     .toString();
    return CommonListPageWidget<CheckInStatisticsListItemBean,
        CheckInStatisticsListResponseBean>(
      enablePullUp: true,
      enablePullDown: true,
      netUrl:ServerApi.BASE_URL + "app/appDayFaceRecord",
      itemBuilder: (BuildContext context, int index,
          CheckInStatisticsListItemBean itemBean) {
        return _toMainRowWidget(itemBean);
      },
      placeHolderFunc: (List<CheckInStatisticsListItemBean> list, Widget child,
          VoidCallback onRefresh) {
        return VgPlaceHolderStatusWidget(
          loadingStatus:  list == null || list.isEmpty && data == null,
          emptyStatus: list == null || list.isEmpty,
          emptyOnClick: () => onRefresh(),
          child: child,
        );
      },
      // needCustomCache: _needCache,
      parseDataFunc: (VgHttpResponse resp) {
        //清空缓存数据
        //todo隐患问题 更新过于频繁导致对应不上问题
        CheckInStatisticsListResponseBean responseBean =
        CheckInStatisticsListResponseBean.fromMap(resp?.data);
        recordNum = responseBean?.data?.eachFaceCnt?.facecnt;
        data=responseBean;
        setState(() {

        });
        return responseBean;
      },
      httpType: VgHttpType.get,
      isInitRefresh: true,
      stateFunc: (state) {
        this.listState = state;
      },
      // customEmptyWidget: type == "未完成"?"自定义":null（null就是默认占位）,
      // customEmptyWidget: _getFilterType() == "01"
      //     ? _defaultEmptyCustomWidget()
      //     : _completeEmptyCustomWidget(),
        queryMapFunc: (int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "current": page ?? 1,
        "size": 1000,
        "dayTime": ((DateTime(time.year, time.month, time.day)?.millisecondsSinceEpoch ?? 0) /
            1000)
            .floor()
            .toString() ?? "",
        //filterType 00未刷脸 01已刷脸
        "face": "01",
        //选择班级
        "classids": "",
        //选择部门
        "departmentids": "",
        //00未选 01选择
        "special": "00",
        //选择终端id（a,b,c）
        "hsns":widget?.hsn??"",
        "orderFlg":"00"
      },
      // needCache: false,
      // cacheKey: _cacheKey,
    );
  }

  Widget _toColumnWidget(CheckInStatisticsListItemBean itemBean) {
    final bool isShowMax = isShowMaxTime(itemBean?.firsttime, itemBean?.lasttime);
    String temperature = "0";
    if(itemBean?.temperature!=""&&itemBean?.temperature!=null){
      if(itemBean?.temperature=="0.0"){
        temperature = "0";
      }else{
        temperature = itemBean?.temperature;
      }
    }
    return Container(
      height: 37,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              CommonConstraintMaxWidthWidget(
                maxWidth: VgToolUtils.getScreenWidth() / 3,
                child: Text(
                  itemBean?.name ?? "名称",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getTextMainColor_D0E0F7(),
                      fontSize: 15,
                      height: 1.2),
                ),
              ),
              Spacer(),
              CommonConstraintMaxWidthWidget(
                maxWidth: VgToolUtils.getScreenWidth() /2,
                child: Text(
                  VgStringUtils.getSplitStr([
                    itemBean?.department?.trim(),
                    // itemBean?.projectname?.trim(),
                    // itemBean?.city?.trim(),
                    itemBean?.classname?.trim(),
                    // itemBean?.coursename?.trim(),
                  ]),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 12,
                  ),
                ),
              )
            ],
          ),
          Row(
            children: <Widget>[
              Container(
                width: 96,
                alignment: Alignment.centerLeft,
                child: Text.rich(
                  TextSpan(children: [
                    TextSpan(text: "${VgToolUtils.getHourAndMinuteStr(itemBean?.firsttime)??"-"}"),
                    TextSpan(text: isShowMax ? " 至 " : "",style: TextStyle()),
                    TextSpan(text: isShowMax ? "${VgToolUtils.getHourAndMinuteStr(itemBean?.lasttime)??"-"}" : ""),
                  ]),
                  style: TextStyle(color: VgColors.INPUT_BG_COLOR, fontSize: 12),
                ),
              ),
              if(isShowMax)
                Text(
                  "${VgToolUtils.getDifferenceTimeStr(itemBean?.firsttime, itemBean?.lasttime) ?? ""}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: VgColors.INPUT_BG_COLOR, fontSize: 12),
                ),
              Spacer(),
              Text(itemBean?.temperature!=null&&itemBean?.temperature!=""&&itemBean?.temperature!="0.0" ?"${_temperatureStr(itemBean) ?? ''}℃" :
              "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color:(double?.parse(temperature)??0)>37.2 ? ThemeRepository.getInstance().getMinorRedColor_F95355() : VgColors.INPUT_BG_COLOR, fontSize: 12),
              )
            ],
          )
        ],
      ),
    );
  }

  String _temperatureStr(CheckInStatisticsListItemBean itemBean){
    if((itemBean?.temperature?.length??0) > 4){
      return itemBean?.temperature?.substring(0,4);
    }else{
      return itemBean?.temperature;
    }
  }
}
